<template>
    <div v-loading="loading" style="width: 100%;">
        <SavePage :title="`${typeName}${form.highwayName}-${form.cycle}计划实施`">
            <template slot="buttons">
                <BaseButton :loading="submitLoading" @click="submit()">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips title="基本信息" :required="true" />
                <el-form ref="form" :model="form" class="size-auto" :rules="rules" :inline="true" size="medium" label-width="86px">
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="公路" prop="roadCode">
                                <el-input v-model="form.highwayName" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="周期" prop="roadCode">
                                <el-input v-model="form.cycle" disabled />
                            </el-form-item>
                        </el-col>
                    </el-row>    
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="制表" prop="tabulation">
                                <el-select v-model="form.tabulation" placeholder="请选择">
                                    <el-option
                                        v-for="item in userOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        style="width: 100%"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="负责人" prop="principal">
                                <el-select v-model="form.principal" placeholder="请选择">
                                    <el-option
                                        v-for="item in userOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="上级批复" prop="higherPrincipal">
                                <el-select v-model="form.higherPrincipal" placeholder="请选择">
                                    <el-option
                                        v-for="item in superLevelUserOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>             
                </el-form>
                <TitleTips title="实施明细" />
                <div class="card-title">日常养护</div>
                <FormCard ref="everydayForm" :form="everydayForm" list-name="dailyList" :rules="everydayRules" />
                <div class="card-title">专项工程</div>
                <FormCard ref="specialForm" :form="specialForm" list-name="specialList" :rules="everydayRules" />
            </template>
        </SavePage>
    </div>
</template>

<script>
import { isNumber2, isNumberOrDecimals } from '@/utils/validate'
import { OrgModel, PlanImpleModel, RoadPlanModel } from '@/models' 
import FormCard from './components/FormCard'

export default {
    name: 'PlanMaintenanceAdd',
    components: {
        FormCard
    },
    data() {
        return {
            loading: true,
            model: new PlanImpleModel(),
            roadPlanModel: new RoadPlanModel(),
            orgModel: new OrgModel(),
            form: {
                roadCode: null,
                tabulation: null,
                principal: null,
                higherPrincipal: null,
            },
            everydayForm: {
                dailyList: []
            },
            specialForm: {
                specialList: []
            },
            everydayRules: {
                completedAmount: [{ validator: this.validNum, trigger: 'blur' }],
                unCompletedAmount: [{ validator: this.validNum, trigger: 'blur' }],
                completedMoney: [{ validator: this.validNum, trigger: 'blur' }],
                unCompletedMoney: [{ validator: this.validNum, trigger: 'blur' }],
                contractMoney: [{ validator: this.validNumberOrDecimals, trigger: 'blur' }],
                unitPrice: [{ validator: this.validNumberOrDecimals, trigger: 'blur' }]
            },
            rules: {
                tabulation: [{ required: true, message: '请选择制表', trigger: 'change' }],
                principal: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                higherPrincipal: [{ required: true, message: '请选择上级批复', trigger: 'change' }]
            },
            userOptions: [],
            superLevelUserOptions: [],
            defalutUserId: null,
            number: null,
            type: 'add',
            typeName: '新建',
            submitLoading: false,
            everydayDetail: [],
            specialDetail: []
        }
    },
    async created() {
        this.getQuery()
        if (this.number) {
            await this.getDetail()
            await Promise.all([this.getEverydayDetail(), this.getSpecialDetail()])
        }
        this.getPlanDetail()
        this.getUserByOrg(this.defalutUserId || this.form.tabulation)
        this.getSuperLevelUser(this.defalutUserId || this.form.tabulation)
    },
    methods: {
        getPlanDetail() {
            this.roadPlanModel.getMonthPlanDetail({ number: this.form.planNumber }, true).then(res => {
                // 日常养护
                this.everydayForm.dailyList = res.dailyList.map(item => {
                    let obj = {
                        planId: item.id,
                        projectName: item.projectName,
                        jobAreaName: item.jobAreaName,
                        prepareCompletionMoney: item.prepareCompletionMoney,
                        workAmount: item.workAmount,
                        arithmeticalUnit: item.arithmeticalUnit
                    }
                    // 如果日常详情列表有，则找到对应的匹配上
                    if (this.everydayDetail.length > 0) {
                        this.everydayDetail.some(m => {
                            if (m.planId === item.id) {
                                obj = Object.assign(obj, m)
                                return true
                            }
                        })
                    }
                    return obj
                })
                // 专项工程
                this.specialForm.specialList = res.specialList.map(item => {
                    let obj = {
                        planId: item.id,
                        projectName: item.projectName,
                        prepareCompletionMoney: item.prepareCompletionMoney
                    }
                    if (this.specialDetail.length > 0) {
                        this.specialDetail.some(m => {
                            if (m.planId === item.id) {
                                obj = Object.assign(obj, m)
                                return true
                            }
                        })
                    }
                    return obj
                })
            }).finally(() => {
                this.loading = false
            })
        },
        getEverydayDetail() {
            return this.model.getEverydayDetail(this.form.number).then(res => {
                this.everydayDetail = res.list.map(item => {
                    return {
                        ...item,
                        startEndTime: item.startEndTime ? item.startEndTime.split(',') : []
                    }
                })
            })
        },
        getSpecialDetail() {
            return this.model.getSpecialDetail(this.form.number).then(res => {
                this.specialDetail = res.list.map(item => {
                    return {
                        ...item,
                        startEndTime: item.startEndTime ? item.startEndTime.split(',') : []
                    }
                })
            })
        },
        getQuery() {
            this.type = this.$route.query.type
            if (this.type === 'edit') {
                this.typeName = '编辑'
                this.number = this.$route.query.number
                // 后端要number
                this.form.number = this.number
            } else if (this.type === 'add') {
                this.typeName = '新建'
                // 新增时，当前用户默认为制表人
                this.defalutUserId = this.$store.getters.avatar.id
                this.form.highwayName = this.$route.query.highwayName
                this.form.cycle = this.$route.query.cycle
                this.form.roadCode = this.$route.query.roadCode
                this.form.planNumber = this.$route.query.planNumber
                this.form.routeLength = this.$route.query.routeLength
            }
        },
        getDetail() {
            return this.model.detail({ number: this.number }).then(res => {
                this.form = res
            })
        },
        validNum(rule, value, callback) {
            if (value && !isNumber2(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        },
        validNumberOrDecimals(rule, value, callback) {
            console.log('valid')
            if (value && !isNumberOrDecimals(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        },
        submit() {
            this.submitLoading = true
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const res1 = await this.$refs['everydayForm'].handleValidate()
                    const res2 = await this.$refs['specialForm'].handleValidate()
                    if (res1 && res2) {
                        // 把开竣工时间数组转为字符串
                        console.log(this.specialForm)
                        this.everydayForm.dailyList.forEach(item => {
                            item.startEndTime && (item.startEndTime = item.startEndTime.toString())
                        })
                        this.specialForm.specialList.forEach(item => {
                            item.startEndTime && (item.startEndTime = item.startEndTime.toString())
                        })
                        const data = { 
                            ...this.form,
                            ...this.everydayForm,
                            ...this.specialForm
                        }
                        this.model.saveOrUpdate(data).then(() => {
                            this.$message({
                                type: 'success',
                                message: this.type === 'edit' ? '修改成功！' : '新建成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        }).finally(() => {
                            this.submitLoading = false
                        })
                    } else {
                        this.submitLoading = false
                    }
                } else {
                    this.submitLoading = false
                }
            })
        },
        // 获取机构下人员
        getUserByOrg(id) {
            this.orgModel.getUserByOrg({ userId: id }).then(res => {
                this.userOptions = res.map(item => {
                    // 如果是新增，把负责人一项默认值设置为当前部门负责人
                    if (this.type === 'add' && item.isPrincipal) {
                        this.form.principal = item.userId
                    }
                    return {
                        value: item.userId,
                        label: item.name
                    }
                })
                // 把制表默认值设置为当前登录用户
                this.type === 'add' && (this.form.tabulation = id)
            })
        },
        // 根据当前用户查询上级部门用户
        getSuperLevelUser(id) {
            this.orgModel.getSuperLevelUser({ userId: id }).then(res => {
                this.superLevelUserOptions = res.map(item => {
                    // 如果是新增，把负责人一项默认值设置为当前部门负责人
                    if (this.type === 'add' && item.isPrincipal) {
                        this.form.higherPrincipal = item.userId
                    }
                    return {
                        value: item.userId,
                        label: item.name
                    }
                })
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.card-title {
    font-size: 14px;
    font-weight: bold;
    color: #171725;
    margin-bottom: 16px;
}
</style>
